package com.zb.service.impl;

import com.zb.dao.BookDao;
import com.zb.dao.OrderDao;
import com.zb.dao.OrderItemDao;
import com.zb.dao.impl.BookDaoImpl;
import com.zb.dao.impl.OrderDaoImpl;
import com.zb.dao.impl.OrderItemDaoImpl;
import com.zb.pojo.*;
import com.zb.service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zb
 * @create 2021-03-09 10:41
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();

    private OrderItemDao orderItemDao = new OrderItemDaoImpl();

    private BookDao bookDao = new BookDaoImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) {

        System.out.println("OrderServiceImpl程序在【"+Thread.currentThread()+"】");

        //生成唯一的订单编号
        String orderId = System.currentTimeMillis()+""+userId;
        Order order = new Order(orderId,new Date(),cart.getTotalPrice(),0,userId);
        //保存订单
        orderDao.saveOrder(order);

//        System.out.println(1/0);

        //遍历购物车中每一个商品项转换成为订单项保存到数据库
        for(Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()){
            //获取每一个购物车中的商品项
            CartItem cartItem = entry.getValue();
            //转换为每一个订单
            OrderItem orderItem = new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId);
            //保存订单项到数据库
            orderItemDao.saveOrderItem(orderItem);

            //更新库存和销量
            Book book = bookDao.queryBookById(cartItem.getId());
            book.setSales(book.getSales()+cartItem.getCount());
            book.setStock(book.getStock()-cartItem.getCount());
            bookDao.updateBook(book);
        }
        //生成订单之后要清空购物车
        cart.clear();
        return orderId;
    }

    @Override
    public List<Order> showAllOrders() {
        return orderDao.queryOrders();
    }

    @Override
    public boolean sendOrder(String orderId) {
        //将Order的status状态该为1
        return orderDao.changeOrderStatus(orderId,1);
    }

    @Override
    public List<OrderItem> showOrderDetail(String orderId) {
        return orderItemDao.queryOrderItemsByOrder(orderId);
    }

    @Override
    public List<Order> showMyOrders(Integer userId) {
        return orderDao.queryOrdersByUserId(userId);
    }

    @Override
    public boolean receiverOrder(String orderId) {
        //将Order的status状态该为2
        return orderDao.changeOrderStatus(orderId,2);
    }
}
